<template>
  <div class="bigbox">
    <!-- 页面导航搜索盒子 -->
    <div class="topbox" :style="{height:!isshow?'80px':'140px'}">
      <el-form ref="form" :model="forms" label-width="60px" label-position="left">
       <el-row :gutter="20">
        <el-col :span="5">
            <el-form-item label="建筑群">
              <!-- <FilterSelect2
                    v-model="form.buildingId"
                    :optionlist="qiyelist"
                    @updateModelValue="changeqiye"
                    :valuekey="{ name: 'name', value: 'id' }"
                  ></FilterSelect2> -->
              <FilterSelect ref="jianzhuqun" :optionlist="qiyelist" :valuekey="{name:'name',value:'id'}" @changeselect="changeqiye" :defaultvalue="buildingId"></FilterSelect>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="用户">
              <FilterSelect2
                v-model="forms.customerId"
                :optionlist="yonghulist"
                :valuekey="{ name: 'customerName', value: 'id' }"
              ></FilterSelect2>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="类型">
              <FilterSelect :optionlist="yomghulist" ref="yonghuleixing" :valuekey="{name:'text',value:'value'}"></FilterSelect>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="状态">
              <el-select size="small" v-model="forms.state" style="width: 100%;" clearable >
                <el-option label="未开户" value="10" class="option"></el-option>
                <el-option label="已开户" value="20" class="option"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6" v-if="isshow">
            <el-form-item label="日期">
              <el-date-picker
                style="width: 100%;"
                clearable 
                size="small"
                v-model="value1"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="isshow?18:4" style="text-align: right;">
            <el-form-item label="">
              <el-button type="primary"  size="small" @click="getlist()">查 询</el-button>
              <el-button type="text" v-if="isshow" class="shou" @click="isshow=!isshow" style=" cursor: pointer;">收起 <i class="el-icon-arrow-up"></i> </el-button>
              <el-button type="text" v-else class="shou" @click="isshow=!isshow" style=" cursor: pointer;">展开 <i class="el-icon-arrow-down"></i> </el-button>
            </el-form-item>
          </el-col>
       </el-row>
      </el-form>
    </div> 
    <!-- 盒子主体 -->
    <div class="bodybox" :style="{height:isshow?'calc(100% - 150px)':'calc(100% - 90px)'}">
      <div class="top">
        <div>开户信息</div>
        <div class="butti">
          <el-button @click="newadd" type="primary" size="small" style="margin-right: 10px;"><i class="el-icon-plus" ></i>新增</el-button>
          <TopTile @command="command" @daochu="daochu" @shuaxin="shuaxin"></TopTile>
        </div>
      </div>
      <!-- 表格区域 -->
      <div class="table">
        <TableColumn
        ref="tabledata"
        :tableData="tableData" 
        :tableConfig="tableConfig" 
        :issize="issize">
        <el-table-column
          prop="state"
          width="100"
            label="状态"
            align="center">
            <template #default="{row}">
              <span v-if="row.state=='未开户'" class="states red"></span>
              <span v-else class="states green"></span>
              <span>{{ row.state}}</span>
            </template>
        </el-table-column>
        <el-table-column
            prop="address"
            label="操作"
            width="160">
            <template #default="{row}">
              <el-tooltip class="item" effect="dark" content="浏览" placement="top">
                <i @click="look(row)" class="el-icon-view" style="color:#1a90fe ;margin:0 10px; cursor: pointer;"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="开户" placement="top">
                <i @click="kaihu(row)" v-if="row.state=='未开户'" class="iconfont icon-yonghukaihu" style="color:#1afe3c ;margin-right: 10px; cursor: pointer;font-size: 17px;"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="销户" placement="top">
                <i @click="xiaohu(row)" v-if="row.state=='已开户'" class="iconfont icon-sanfangcunguanxiaohu" style="color:#fdd143;margin-right: 10px; cursor: pointer;"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="编辑" placement="top">
                <i @click="xiugai(row)" v-if="row.state=='未开户'" class="el-icon-edit" style="color:#1a90fe ;margin-right: 10px; cursor: pointer;"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="删除" placement="top">
                <i @click="shanchu(row)" v-if="row.state=='未开户'" class="el-icon-delete" style="color: red;cursor: pointer;margin-right: 10px;"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="开户编辑" placement="top">
                <i @click="updatekaihu(row)" v-if="row.state=='已开户'" class="el-icon-edit-outline" style="color:#1a90fe;margin-right: 10px; cursor: pointer;"></i>
              </el-tooltip>
            </template>
        </el-table-column>
      </TableColumn>
      <!-- 底部分页 -->
      <div class="fenye">
          <el-pagination
                background
                layout="prev, pager, next"
                :current-page.sync="pages.pageNo"
                :page-size="20"
                @current-change="getlist"
                :total="+totalCount">
          </el-pagination>
      </div>
      </div>
      <!-- 销户dialog弹窗区域 -->
      <div class="dialog">
        <el-dialog
        title="销户信息"
        :visible.sync="dialogVisible"
        width="40%">
        <div>
          <el-form ref="form" :model="form" :rules="rules" label-position="right" label-width="100px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="用户编号">
                  <el-input disabled v-model="form.customerNo" size="small" ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="用户姓名" >
                  <el-input v-model="form.contactName" size="small" disabled></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="房间名称" >
                  <el-select multiple v-model="form.roomIds"  size="small" style="width: 100%;" disabled>
                      <el-option v-for="(item,index) in roomlist" :key="index" :label="item.name" :value="item.id" class="option"></el-option>
                    </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="合约开始时间" >
                  <el-date-picker
                  disabled
                    style="width: 100%;"
                    value-format="yyyy-MM-dd"
                    size="small"
                    v-model="form.contractStartData"
                    type="date"
                    placeholder="选择日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合约结束时间" >
                  <el-date-picker
                    style="width: 100%;"
                    disabled
                    value-format="yyyy-MM-dd"
                    size="small"
                    v-model="form.contractEndData"
                    type="date"
                    placeholder="选择日期">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="联系电话">
                  <el-input v-model="form.contactPhone" size="small" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="备注" >
                  <el-input v-model="form.orgname" size="small" disabled></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="告警金额1" >
                  <el-input v-model="form.firstAlarmAmount" size="small" disabled>
                    <span  slot="suffix">元</span>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="告警金额2" >
                  <el-input v-model="form.secondAlarmAmount" size="small" disabled>
                    <span  slot="suffix">元</span>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="通知时间" >
                  <el-input v-model="form.firstNotificationDays" size="small" disabled>
                    <span  slot="suffix">天</span>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="连续通知天数" >
                  <el-input v-model="form.continuousNotificationDays" size="small" disabled>
                    <span  slot="suffix">天</span>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <span slot="footer">
          <el-button size=small @click="dialogVisible = false">取 消</el-button>
          <el-button type="danger" size=small @click="arrxiaohu">直接销户</el-button>
        </span>
      </el-dialog>
      </div>
      <!-- 开户后编辑弹窗 -->
      <div class="kaihuxinxi">
        <el-dialog
          title="编辑"
          :visible.sync="kaihudialogVisible"
          width="30%">
          <div>
            <el-tree :data="data"
             show-checkbox 
             :props="defaultProps"
             highlight-current
             check-strictly
             default-expand-all
              ref="tree"></el-tree>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button size="small" @click="kaihudialogVisible = false">取 消</el-button>
            <el-button type="primary" size="small"  @click="treesure">确 定</el-button>
          </span>
        </el-dialog>
      </div> 
      <!-- 新增用dialog区域 -->
      <div class="kaihuxinxi">
        <el-dialog
          title="客户开户信息"
          :visible.sync="dialogVisibles"
          width="55%">
          <div>
            <div style="display: flex;justify-content: space-between;
            margin-bottom: 20px;padding-bottom: 10px;"
            >
              <span style="color: #303133;font-size: 18px;">客户开户信息</span>
              <span @click="quxiao"><i class="el-icon-close"></i></span>
            </div>
            <el-divider></el-divider>
            <el-form ref="openform" :model="openform" :rules="openrules" label-position="right" label-width="100px" @submit="onSubmit" >
              <el-row>
                <el-col :span="12">
                  <el-form-item label="建筑群" prop="buildingId">
                    <el-select v-model="openform.buildingId" placeholder="请选择建筑群" filterable  :disabled="flag"  size="small" style="width: 100%;" @change="change">
                      <el-option v-for="(item,index) in qiyelist" :key="index" :label="item.name" :value="item.id" class="option"></el-option>
                    </el-select>
                </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="客户类型" prop="customerType">
                    <el-radio-group v-model="openform.customerType">
                      <el-radio v-for="(item,index) in yomghulist" :disabled="flag" :key="index" :label="item.value">{{ item.text }}</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
              <template >
                <div v-show="openform.customerType=='COMPANY'">
                  <el-row>
                  <el-col :span="12">
                    <el-form-item label="企业名称" prop="customerName">
                      <el-input v-model="openform.customerName" size="small" :disabled="updateflag" placeholder="请输入企业名称">
                        <button type="button"  slot="suffix" style="width: 50px;color: #fff;border-radius: 3px;
                        height: 24px;background: #1890FF;border: none;" @click="yanzheng">验证</button>
                      </el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="企业编码" prop="companyNo">
                      <el-input v-model="openform.companyNo" size="small" :disabled="flag" placeholder="请输入企业编码"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="客户编号" prop="customerNo">
                      <el-input v-model="openform.customerNo" size="small" :disabled="updateflag" placeholder="请输入客户编号"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="联系人" prop="contactName">
                      <el-input v-model="openform.contactName" size="small" :disabled="updateflag" placeholder="请输入联系人"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                </div>

              </template>
              <template >
                <div v-show="openform.customerType== 'USER'">
                  <el-row>
                  <el-col :span="12">
                    <el-form-item label="用户名" prop="customerName">
                      <el-input v-model="openform.customerName" size="small" :disabled="updateflag" placeholder="请输入用户名"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="用户编号" prop="customerNo">
                      <el-input v-model="openform.customerNo" size="small" :disabled="updateflag" placeholder="请输入用户编号"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                </div>

              </template>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="联系电话" prop="contactPhone">
                    <el-input v-model="openform.contactPhone" size="small" :disabled="updateflag" placeholder="请输入联系电话"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="开户日期" prop="accountOpenData">
                    <el-date-picker
                      size="small"
                      style="width: 100%;"
                      :disabled="updateflag"
                      format='yyyy-MM-dd'
                      v-model="openform.accountOpenData"
                      type="date"
                      placeholder="选择日期">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="合约开始时间">
                    <el-date-picker
                      size="small"
                      :disabled="updateflag"
                      style="width: 100%;"
                      format='yyyy-MM-dd'
                      v-model="openform.contractStartData"
                      type="date"
                      placeholder="选择日期">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="合约结束时间">
                    <el-date-picker
                    :disabled="updateflag"
                      size="small"
                      style="width: 100%;"
                      format='yyyy-MM-dd'
                      v-model="openform.contractEndData"
                      type="date"
                      placeholder="选择日期">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="房间">
                    <el-select multiple v-model="meterReadInfo" :disabled="flag" filterable placeholder="请选择房间 可多选"  size="small" style="width: 100%;" @change="changeroom">
                      <el-option v-for="(item,index) in roomlist" :key="index" :label="item.name" :value="item.id" class="option"></el-option>
                    </el-select>
                </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-button type="primary" @click="kaihuadd" size="small" v-if="buttonkong" style="height: 30px;width: auto;padding: 0 10px;margin:5px 0 0 20px;">增加表计</el-button>
                </el-col>
              </el-row>
              <template>
                <div>
                  <el-table
                  border
                    :header-cell-style="{'text-align':'center',background:'#f5f5f5'}"
                    :data="tableDatas"
                    style="width: 100%">
                    <el-table-column
                      prop="roomName"
                      label="房间名称">
                    </el-table-column>
                    <el-table-column
                      prop="meterName"
                      label="电表名称">
                    </el-table-column>
                    <el-table-column
                      prop="initialValue"
                      label="初始示数"
                      width="400">
                      <template #default="{row}">
                        <div>
                          <div style="margin-bottom: 8px;" v-show="row.energyType=='ELEC'">
                            <span style="margin-right: 5px;">&nbsp;&nbsp;&nbsp;尖:</span>
                            <span style="margin-right: 5px;"><el-input size="mini" style="width: 40%;" v-model="row.initialValue.sharpValue" placeholder="请输入内容"></el-input></span>
                            <span style="margin-right: 5px;">峰:</span>
                            <span style="margin-right: 5px;"><el-input size="mini" style="width: 40%;" v-model="row.initialValue.peakValue" placeholder="请输入内容"></el-input></span>
                          </div>
                          <div  style="margin-bottom: 8px;" v-show="row.energyType=='ELEC'">
                            <span style="margin-right: 5px;">&nbsp;&nbsp;&nbsp;平:</span>
                            <span style="margin-right: 5px;"><el-input size="mini" style="width: 40%;" v-model="row.initialValue.flatValue" placeholder="请输入内容"></el-input></span>
                            <span style="margin-right: 5px;">谷:</span>
                            <span><el-input size="mini" style="width: 40%;" v-model="row.initialValue.valleyValue" placeholder="请输入内容"></el-input></span>
                          </div>
                          <div>
                            <span style="margin-right: 5px;">深谷:</span>
                            <span style="margin-right: 5px;"><el-input size="mini" style="width: 40%;" v-model="row.initialValue.deepValleyValue" placeholder="请输入内容"></el-input></span>
                            <span style="margin-right: 5px;">总:</span>
                            <span style="margin-right: 5px;"><el-input size="mini" style="width: 40%;" v-model="row.initialValue.totalValue" placeholder="请输入内容"></el-input></span>
                          </div>
                        </div>
                      </template>
                    </el-table-column>
                    <el-table-column
                        prop="address"
                        label="操作"
                        align="center"
                        width="120">
                        <template #default="{row}">
                          <el-button :disabled="updateflag" @click="dushi(row)" 
                          style="height: 30px;width: 96px;padding: 0 10px;margin:0 0 10px 10px;" type="primary" icon="el-icon-edit">读取示数</el-button>
                          <el-button type="warning" :disabled="updateflag" v-if="row.isnew&&buttonkong" @click="zhuordel(row)"
                          style="height: 30px;width: 96px;padding: 0 10px;" class="el-icon-delete">删除表计</el-button>
                          <el-button type="danger" :disabled="updateflag" v-else-if="buttonkong" @click="zhuordel(row)"
                          style="height: 30px;width: 96px;padding: 0 10px;" class="el-icon-delete">注销表计</el-button>
                        </template>
                    </el-table-column>
                  </el-table>
                </div>
              </template>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="告警金额1">
                    <el-input v-model="openform.firstAlarmAmount" :disabled="updateflag" size="small" placeholder="请输入告警金额1">
                      <span style="color: #000;" slot="suffix">元</span>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="告警金额2">
                    <el-input v-model="openform.secondAlarmAmount" :disabled="updateflag" size="small" placeholder="请输入告警金额2">
                      <span style="color: #000;" slot="suffix">元</span>
                    </el-input>
                  </el-form-item></el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="通知时间">
                    <el-input v-model="openform.firstNotificationDays" :disabled="updateflag" size="small" placeholder="请输入通知时间">
                      <span style="color: #000;" slot="suffix">天</span>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="连续通知时间">
                    <el-input v-model="openform.continuousNotificationDays" :disabled="updateflag" size="small" placeholder="请输入连续通知时间">
                      <span style="color: #000;" slot="suffix">天</span>
                    </el-input>
                  </el-form-item></el-col>
              </el-row>
            </el-form>
          </div>
          <span slot="footer" >
            <el-button  @click="quxiao" size="small">取消</el-button>
            <el-button v-show="!flag"  type="primary" size="small" @click="baocun">保存</el-button>
            <el-button v-if="buttonkong"  type="primary" size="small" @click="kaihubaocun">保存</el-button>
          </span>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
// import {gettablelistapi} from '@/api/prwpaid/user-manage/OpenAaccount'
import FilterSelect from '@/components/FilterSelect'
import { getEnterpriseData } from '@/api/companyRegister'
import { getzidianxialaapi } from '@/api/guidelines'
import {
  gettablelistapi, getweipeilistapi, getroomgetbiaoapi, postopenkaihuapi, postxiaohuapi, postxiugaiapi,postkaihuhouupdateapi,
  postkaihulaapi,getmetershishuapi,postdelhuapi,getroomtreelistapi} from '@/api/prwpaid/user-manage/OpenAaccount'
import {getloginlistapi,getyanzhengapi} from '@/api/prwpaid/file-management/Architectural-complex'
import TopTile from '@/components/TopTitle/index.vue'
import TableColumn from '@/components/Table/index.vue'
import {exportexcel} from '@/utils/excel'
export default {
  name: 'CallPoliceIndex',
  components: {
    TopTile,
    FilterSelect,
    TableColumn
  },
  data() {
    return {
      flag:false,
      updateflag: false,
      buttonkong:false,
      dialogVisibles: false,
      kaihudialogVisible:false,
      value1:['',''],
      yomghulist:[],
      dialogVisible:false,
      issize: 'medium',
      forms:{state:''},
      qiyelist: [],
      tableData: [],
      tableConfig: [
        { label: '序号', type: 'index', center: 'center', width: '50' },
        { label: '客户类型', prop: 'customerTypeName' , width: '80'},
        { label: '建筑群', prop: 'buildingsName' },
        { label: '开户时间', prop: 'accountOpenData' ,center:'center', width: '100'},
        { label: '企业/用户编号', prop: 'customerNo' },
        { label: '企业/用户', prop: 'customerName' },
        { label: '联系人', prop: 'contactName' , width: '70'},
        { label: '联系电话', prop: 'contactPhone' ,center:'center', width: '120'},
        { label: '合约开始时间', prop: 'contractStartData' ,center:'center', width: '110'},
        { label: '合约结束时间', prop: 'contractEndData' ,center:'center', width: '110'},
      ],
      roomlist:[],
      form: {},
      rules: {},
      openform: {companyDossierInfoId:'',firstAlarmAmount:'200',secondAlarmAmount:'100',firstNotificationDays:'1',continuousNotificationDays:'1'},
      meterReadInfo:[],
      openrules: {},
      tableDatas: [],
      pages: {
        pageNo: 1,
        pageSize:20
      },
      totalCount: '',
      beforeUpdateRoomIds: [],
      beforeUpdateMeterReadInfo:[],
      defaultProps:{
        label: 'name',
        children:'sonList'
      },
      data: [],
      zhuxiaolist: [],
      buildingId:'',
      yonghulist:[],
      isshow:false
    };
  },

  async mounted() {
    this.gettime()
    const res = await getloginlistapi()
    this.qiyelist = res.data.list
    const localbuildingId = localStorage.getItem('buildingId')
    const isBuildIdInArray = this.qiyelist.some(item => item.id == localbuildingId);
    this.$set(this,'buildingId',isBuildIdInArray?localbuildingId:this.qiyelist[0].id)
    this.changeqiye(this.buildingId)
    // 获取收费类型
    const yonghu = await getzidianxialaapi({ dictType: 'MBM_CUSTOMER_TYPE' })
    this.yomghulist = yonghu.data.list
    this.$set(this.openform,'customerType','COMPANY')
    this.getlist()
  },

  methods: {
    // 企业下拉
    async changeqiye(val) {
      localStorage.setItem('buildingId', val)
      const ress = await gettablelistapi({
        pageNo: 0, pageSize: 500,
        startDate: '', endDate: '', 
        state:'20',buildingId:val,customerType:''
      })
      this.yonghulist = ress.data.list
    },
    // 开户修改弹窗确认
    async kaihubaocun() {
      const {accountOpenData,continuousNotificationDays,contractEndData,contractStartData,firstAlarmAmount,firstNotificationDays,id,
        secondAlarmAmount,customerNo,customerName,contactName,contactPhone,roomIds
      }=this.openform
      const stopMpIds=this.zhuxiaolist.map(ele=>ele.measuringPointId)
      const meterReadInfo = this.tableDatas.map(ele=>{
        const {measuringPointId,initialValue,createDate,roomName,meterName,roomId,meterId,energyType}=ele
        return {
          measuringPointId:ele.id?ele.id:ele.measuringPointId,
          initialValue:ele.initialValue,
          createDate:ele.createDate,
          roomName:ele.roomName,
          meterName:ele.meterName,
          roomId:ele.roomId,
          meterId:ele.meterId,
          energyType:ele.energyType
        }
      })
      await postkaihuhouupdateapi({
        accountOpenData,continuousNotificationDays,contractEndData,contractStartData,firstAlarmAmount,firstNotificationDays,id,roomIds: this.meterReadInfo.join(','),
        secondAlarmAmount,customerNo,customerName,contactPhone,contactName,meterReadInfo:JSON.stringify(meterReadInfo),stopMpIds:stopMpIds.join(','),
        beforeUpdateRoomIds:roomIds
      }).then(res=>{
        this.$message({
            type: res.code=='200'?'success':'warning',
            message: res.code=='200'?'修改成功':res.message
          })
      })
      this.quxiao()
      this.getlist()
    },
    // 新增表计
    async kaihuadd() {
      this.kaihudialogVisible = true
      const { data: { entity:{sonList}} } = await getroomtreelistapi({ buildingId: this.openform.buildingId, customerId: this.openform.id })
      this.data=this.processArray(sonList)
    },
    processArray(arr) {
        return arr.map(item => {
            if (item.sonList && item.sonList.length > 0) {
                item.sonList = this.processArray(item.sonList);
            }
            if (item.type !== 3) {
                return { ...item, disabled: true };
            } else {
                return { ...item, disabled: false };
            }
        });
    },
    // 禁用节点
    jinyong(list){
      list.map(ele=>{
        if(ele.type!=='1') {
          ele['disabled']=true
        }
        return ele
      })
      if(list.sonList){
        this.jinyong(list.sonList)
      }
    },
    // 新增表计弹窗确认
    treesure() {
      const arr = this.$refs.tree.getCheckedNodes(false, true)
      arr.forEach(ele => {
          this.tableDatas.push({
            ...ele,isnew:true, initialValue: {
              sharpValue: 0, peakValue: 0, flatValue: 0,
              valleyValue:0,totalValue:0,deepValleyValue:0
            }, createDate: ''
          })
          this.tableDatas.forEach(item => {
            if (ele.roomId !== +item.roomId) {
              if(!this.meterReadInfo.some(val=>val==+ele.roomId))this.meterReadInfo.push(+ele.roomId)
            }
          })   
      });
      this.kaihudialogVisible = false
    },
    // 注销或者删除表计
    zhuordel(row) {
      this.$confirm('此操作将删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          if (!row.isnew) {
            this.zhuxiaolist.push(row)
          }
          this.tableDatas = this.tableDatas.filter(ele => ele.meterId !== row.meterId)
          if (!this.tableDatas.some(ele => ele.roomId== row.roomId)) {
            this.meterReadInfo = this.meterReadInfo.filter(item =>item !== +row.roomId)
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 弹窗确定
    async baocun() {
      const meterReadInfo = JSON.stringify(this.tableDatas)
      const array=JSON.stringify(this.beforeUpdateMeterReadInfo)
      this.openform.id ? postxiugaiapi({
        ...this.openform,
        contactName:this.openform.customerType== 'USER'?this.openform.customerName:this.openform.contactName ,
        meterReadInfo: meterReadInfo,
        roomIds: this.meterReadInfo.join(','),
        beforeUpdateMeterReadInfo:array ,
        beforeUpdateRoomIds:this.beforeUpdateRoomIds.join(',')
      }).then(res => {
        this.$message({
            type: res.code=='200'?'success':'warning',
            message: res.code=='200'?'修改成功':res.message
          })
      })
        : await postopenkaihuapi({
          ...this.openform,
        contactName:this.openform.customerType== 'USER'?this.openform.customerName:this.openform.contactName ,
        meterReadInfo: meterReadInfo,
        roomIds:this.meterReadInfo.join(',')
        }).then(res => {
        this.$message({
            type: res.code=='200'?'success':'warning',
            message: res.code=='200'?'新增成功':res.message
          })
      })
     this.quxiao()
     this.getlist()
    },
    kaihu(row) {
      this.$confirm('此操作将为此用户开户, 是否继续开户?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await postkaihulaapi({ id: row.id })
          this.getlist() 
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消开户'
          })
        })
    },
    // 读取表计示数
    async dushi(row) {
      const measuringPointId=row.measuringPointId?row.measuringPointId:row.id
      const { data: { entity } } = await getmetershishuapi({ measuringPointId: measuringPointId, meterType: row.energyType })
      this.$message.success('读取成功')
      this.tableDatas.forEach(ele => {
        if (ele.meterId == row.meterId) {
            ele.initialValue.flatValue=entity.flatValue?entity.flatValue:0
            ele.initialValue.sharpValue=entity.sharpValue?entity.sharpValue:0
            ele.initialValue.peakValue=entity.peakValue?entity.peakValue:0
            ele.initialValue.valleyValue=entity.valleyValue?entity.valleyValue:0
            ele.initialValue.totalValue=entity.totalValue?entity.totalValue:0
            ele.initialValue.deepValleyValue=entity.deepValleyValue?entity.deepValleyValue:0
          }
      })
    },
     // 删除
     shanchu(val) {
      this.$confirm('此操作将永久删除该档案, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await postdelhuapi({ id: val.id })
          this.getlist()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      
    },
    // 表格数据修改
    async xiugai(val) {
      this.dialogVisibles = true
      this.openform = { ...val }
      const res = await getweipeilistapi({ buildingId: val.buildingId, customerId: val.id })
      this.roomlist=res.data.list
      const array = val.roomIds.split(',').map(ele => +ele)
      this.meterReadInfo=array
      this.tableDatas = JSON.parse(val.meterReadInfo)
      this.beforeUpdateRoomIds = array
      this.beforeUpdateMeterReadInfo = this.tableDatas
    },
    // 查询
    look(row) {
      this.flag = true
      this.buttonkong=false
      this.updateflag=true
      this.xiugai(row)
    },
    // 开户后编辑
    updatekaihu(row) {
      this.flag = true
      this.updateflag = false
      this.buttonkong=true
      this.xiugai(row)

    },
    // 新增
    newadd() {
      this.dialogVisibles = true
      this.flag = false
      
      this.openform.buildingId = this.buildingId
      this.change(this.openform.buildingId)
    },
    // 弹窗取消
    quxiao() {
      this.flag = false
      this.updateflag=false
      this.buttonkong=false
      this.zhuxiaolist=[]
      this.meterReadInfo=[]
      this.openform={}
      this.openform={companyDossierInfoId:'',firstAlarmAmount:'200',secondAlarmAmount:'100',firstNotificationDays:'1',continuousNotificationDays:'1'}
      this.tableDatas=[]
      this.dialogVisibles = false
      this.$set(this.openform, 'customerType', 'COMPANY')
      this.gettime()
    },
    // 获取表格数据
    async getlist() {
      this.$refs.tabledata.loading = true
      const res = await gettablelistapi({
        pageNo: this.pages.pageNo - 1, pageSize: this.pages.pageSize,customerType:this.$refs.yonghuleixing.brandId,
        startDate: this.value1[0], endDate: this.value1[1],  ...this.forms,buildingId:this.$refs.jianzhuqun.brandId
      })
      this.tableData = res.data.list
      this.totalCount = res.data.totalCount
      this.$refs.tabledata.loading=false
    },
    // 房间下拉
    async changeroom(val) {
      this.tableDatas = []
      for (let i = 0; i < val.length; i++){
        const { data: { list } } = await getroomgetbiaoapi({ roomIds: val[i] ,meteringType:'USER'})
        list.forEach(ele => {
          this.tableDatas.push({
            ...ele, initialValue: {
              sharpValue: 0, peakValue: 0, flatValue: 0,
              valleyValue:0,totalValue:0,deepValleyValue:0
          },createDate:''})
        });
      }
    },
    // 建筑群下拉
    async change(val) {
      const res = await getweipeilistapi({ buildingId: val, customerId: '' })
      this.roomlist = res.data.list
      this.meterReadInfo = []
      this.tableDatas=[]
    },
    // 验证
    async yanzheng() {
      const res = await getyanzhengapi({ companyName:this.openform.customerName})
      if (res.code !== 200) {
        const ress = await getEnterpriseData(this.openform.customerName)
        if (ress.data.code == 200) {
          this.$set(this.openform,'companyNo',ress.data.data.data.creditNo)
          this.$set(this.openform,'contactName',ress.data.data.data.legalPerson)
          this.$message.success('验证成功')
        } else {
          this.$message.warning('查询无结果')
        }
      } else {
        this.$set(this.openform,'companyDossierInfoId',res.data.entity.id)
        this.$set(this.openform,'companyNo',res.data.entity.enterpriseCode)
        this.$set(this.openform,'contactName',res.data.entity.manageUserName)
        this.$set(this.openform,'contactPhone',res.data.entity.manageUserMobile)
        this.$message.success('验证成功')
      }
    },
   // 调节表格密度
  command(val) {
      if (val === '默认') {
        this.issize = 'medium'
      } else if (val === '中等') {
        this.issize = 'small'
      } else {
        this.issize = 'mini'
      }
    },
    // 导出
    daochu() {
      exportexcel(
        'mbm-microservice-biz/mbm/customer/exportExcel',
        { startDate: this.value1[0], endDate: this.value1[1], state: '01', ...this.forms },
        '开户信息'
      )
    },
    // 刷新列表
    shuaxin() {
      this.getlist()
      this.$message.success('列表刷新成功')
    },
    // 销户
    async xiaohu(val) {
      this.dialogVisible = true
      this.form = { ...val }
      getweipeilistapi({ buildingId: val.buildingId, customerId: val.id }).then(res => {
        this.roomlist = res.data.list
        const array = val.roomIds.split(',').map(ele => +ele)
        this.form.roomIds=array
      })
    },
    // 销户确认
    arrxiaohu() {
      this.$confirm('此操作将注销该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await postxiaohuapi({ id: this.form.id })
          this.dialogVisible = false
          this.getlist() 
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    //  获取当前时间错
    gettime() {
      const date = new Date()
      const year = date.getFullYear() // 年
      const mon = date.getMonth() + 1 // 月
      const month=mon<10?'0'+mon:mon
      const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      this.$set(this.openform,'accountOpenData',year + '-' + month + '-' + day)
      this.$set(this.openform,'contractStartData',year + '-' + month + '-' + day)
      this.$set(this.openform,'contractEndData',year+1 + '-' + month + '-' + day)
    },
    onSubmit(event) {
      event.preventDefault(); // 阻止默认的提交事件
      // 处理表单提交逻辑
   }
  },
  watch: {
    dialogVisibles(val) {
      if (!val) {
        this.quxiao()
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.option{
  padding-left: 10px;
}
.bigbox{
  height: 100%;
  padding: 10px;
  .topbox{
    height: 80px;
    padding:20px;
    // line-height: 80px;
    background-color: #fff;
    margin-bottom: 10px;
    span{
      margin-right: 15px;
    }
  }
  .bodybox{
    //height: calc(100% - 90px);
    background-color: #fff;
    padding: 20px;
    .top{
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
      .butti{
        display: flex;
      }
    }
    .table{
      height: 90%;
      .states{
        display: inline-block;
        width: 10px;
        height: 10px;
        margin-right: 10px;
        border-radius: 50%;
      }
      .red{
        background-color:red;
      }
      .green{
        background-color: #13ce66;
      }
      .fenye{
        text-align: right;
        margin-top: 10px;
      }
    }
    // .dialog{
    //   .sure{
    //     color: #fff;
    //     width: auto;
    //     background-color: red;
    //     padding: 0 10px;
    //   }
    // }
  }
}
::v-deep .el-radio{
  margin-right: 20px;
}
::v-deep .el-form-item__error{
  padding-top: 0 !important;
}
::v-deep .el-row{
  margin-bottom: 7px;
}
::v-deep .el-divider--horizontal{
  margin-bottom: 20px;
}

::v-deep .el-dialog__header{
  display: none;
}
::v-deep .el-dialog__footer{
  text-align: center;
}
// ::v-deep .el-button--danger, .el-button--warning{
//   margin-left: 0;
//   margin-top: 5px;
// }
</style>